from jili.core.convert import converttype
from bs4 import BeautifulSoup
import pandas as pd
from jili.report import openweb
import re
class html():
    def __init__(self,htmlstr="",file="",name="实验报告"):
        self.isecharts=False
        self.url=""
        if htmlstr!="":
            if file!="":
                self.soup = BeautifulSoup(open(file),"lxml")
                if self.soup.title.string=="Echarts":
                    self.isecharts=True
                h=BeautifulSoup(htmlstr,"lxml")
                for i in h.body.children:
                    self.soup.body.append(i)
            else:
                self.soup = BeautifulSoup(htmlstr,"lxml")
            if name!="":
                self.soup.title.string=name
                t=self.gettitle(name,"h1")
                self.soup.body.insert(0,t)
        else:
            if file!="":
                self.soup = BeautifulSoup(open(file),"lxml")
                if self.soup.title.string=="Echarts":
                    self.isecharts=True
            else:
                self.soup = BeautifulSoup(self.__head(),"lxml")
            if name!="":
                self.soup.title.string=name
                t=self.gettitle(name,"h1")
                self.soup.body.insert(0,t)
    def gettitle(self,name,titletype="h4"):
        htile=self.soup.new_tag(titletype)
        htile["align"]="center"
        htile.string=name
        return htile
    def sethead(self,name):
        if name!="":
            self.soup.title.string=name
            t=self.gettitle(name,"h1")
            self.soup.body.insert(0,t)
        return self
    def __head(self,name="实验报告"):
        return """"
            <head>
                <meta charset="utf-8">
                <title>"""+name+"""</title>
            </head>
            """
    def addnode(self,tag,atrr):
        h=self.soup.new_tag(tag)
        for k,v in atrr.items():
            h[k]=v
        self.soup.body.append(h)
        return self
    def addfile(self,file,usehtml=False):
        h = BeautifulSoup(open(file),"lxml")
        if h.title.string in ["Echarts","Awesome-pyecharts"]:
            usehtml=True
        if usehtml:
            if self.isecharts:
                for i in h.body.children:
                    self.soup.body.append(i)
            else:
                self.isecharts=True
                n=0
                for i in self.soup.body.children:
                    h.body.insert(n,i)
                    n=n+1
                h.title.string=self.soup.title.string
                self.soup=h
        else:
            for i in h.body.children:
                self.soup.body.append(i)
    def addtitle(self,name,titletype="h4",align="center"):
        htile=self.soup.new_tag(titletype)
        htile["align"]=align
        htile.string=name
        self.soup.body.append(htile)
        return self
    def addtext(self,text,align="",insertpos=""):
        htile=self.soup.new_tag("p")
        if align!="":
            htile["align"]=align
        htile.string=text
        if insertpos=="":
            self.soup.body.append(htile)
        else:
            self.soup.body.insert(insertpos,htile)
        return self
    def addtable(self,table,insertpos=""):
        if not isinstance(table,pd.DataFrame):
            t=converttype(table,"df")
        else:
            t=table
        if isinstance(t,pd.DataFrame):
            pd.set_option('max_colwidth',200)
            a =t.to_html()
            a= """<div align="center">
                    """+a+"""
                </div>"""
        else:
            a=""
        if a!="":
            h= BeautifulSoup(a,"lxml")
            for i in h.body.children:
                if insertpos=="":
                    self.soup.body.append(i)
                else:
                    self.soup.body.insert(insertpos,i)
                    insertpos=insertpos+1
        return self
    def addfig(self,fig,insertpos=""):
        """
        div=self.soup.new_tag("div")
        div["align"]="center"
        fig=self.soup.new_tag("img")
        fig["src"]=fig
        fig["ail"]=u"no figure"
        div.append(fig)
        """
        a= """<div align="center">
                <img src="""+fig+"""  alt="no fig" />
            </div>"""
        h= BeautifulSoup(a,"lxml")
        for i in h.body.children:
            if insertpos=="":
                self.soup.body.append(i)
            else:
                self.soup.body.insert(insertpos,i)
                insertpos=insertpos+1
        return self
    def to_string(self):
        return self.soup.prettify()
    def generate_toc(self):
        toc = []
        for header in self.soup.find_all(re.compile('^h[1-6]$')):
            title = ''.join(header.find_all(text=True))
            href = '#' + header.get('id') if header.get('id') else ''
            toc.append(f'<li><a href="{href}">{title}</a></li>')
        return ''.join(toc) if toc else None
    def add_toc(self):
        toc = self.generate_toc()
        if toc:
            toc_div = self.soup.new_tag('div')
            toc_div['class'] = 'table-of-contents'
            toc_div.append(self.soup.new_tag('ul', html_contents=toc))
            self.soup.body.insert(0, toc_div)
    def save(self,url):
        # self.add_toc()
        h=self.to_string()
        name0=url
        f = open(name0,"w",encoding='utf8')
        f.write(h)
        f.close()
        self.url=name0
    def show(self,name="",refresh=False):
        if self.url=="" or refresh:
            self.save()
            openweb(self.url)
        else:
            openweb(self.url)
class text():
    def __init__(self,title=""):
        
        self.title=title
        self.body=[]
        self.url=""
    def sethead(self,title):
        self.title=title
        return self
    def __head(self):
        return """"<html>
            <head>
                <meta charset="utf-8">
                <title>"""+self.title+"""</title>
            </head>
            <body>"""
    def end(self):
        return """
                </body>
            <html>"""
    def addtext(self,text,headtype="h4"):
        a= """<div align="center">
                <"""+headtype+""" align="center">"""+text+"""</"""+headtype+""">
            </div>"""
        self.body.append(a)
        return self
    def addtable(self,table):
        if not isinstance(table,pd.DataFrame):
            t=converttype(table,"df")
        else:
            t=table
        if isinstance(t,pd.DataFrame):
            pd.set_option('max_colwidth',200)
            a =t.to_html()
            a= """<div align="center">
                    """+a+"""
                </div>"""
        else:
            a=""
        self.body.append(a)
        return self
    def addfig(self,fig):
        a= """<div align="center">
                <img src="""+fig+"""  alt="no fig" />
            </div>"""
        self.body.append(a)
        return self
    def to_string(self):
        h=self.__head()
        for i in self.body:
            h=h+i
        h=h+self.end()
        return h
    def show(self,name="",refresh=False):
        if self.url=="" or refresh:
            h=self.to_string()
            if name=="":
                name0=self.title+".html"
            else:
                name0=name+".html"
            f = open(name0,"w",encoding='utf8')
            for eachline in h:
                f.write(eachline)
            f.close()
            
            self.url=name0
            openweb(self.url)
        else:
            openweb(self.url)